package com.example.shirodemo.demos.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping("/login")
    public String login(String username, String password) {
        // 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        // 封装凭证
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        // 身份认证，失败抛异常
        try {
            currentUser.login(token);
        } catch (UnknownAccountException e) {
            return "error: 用户名不存在";
        } catch (IncorrectCredentialsException e) {
            return "error: 密码错误";
        } catch (Exception e) {
            return "error: 未知异常";
        }
        // 记住我
        token.setRememberMe(true);
        return "login ok";
    }

    @RequestMapping("/save")
    // 必须认证通过
    @RequiresAuthentication
    // 认证通过或记住我，搭配登录接口
    @RequiresUser
    public String save() {
        return "save ok";
    }

    @RequestMapping("/form")
    // 匿名访问，必须访客，认证之后不能访问
    @RequiresGuest
    public String form() {
        return "form ok";
    }

    @RequestMapping("/list")
    // 必须由指定的权限
    @RequiresPermissions("user:list")
    public String list() {
        return "list ok";
    }

    @RequestMapping("/listData")
    // 必须有指定的角色
    @RequiresRoles("admin")
    public String listData() {
        return "listData ok";
    }
}
